package com.imc.platform.base.wxOauth2Token.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.imc.core.annotation.Logs;
import com.imc.core.utils.AESUtils;
import com.imc.core.utils.DateUtils;
import com.imc.core.utils.MysqlUtil;
import com.imc.platform.base.user.dao.repository.UserRepository;
import com.imc.platform.base.user.pojo.User;
import com.imc.platform.base.user.service.ISSOService;
import com.imc.platform.base.wxOauth2Token.http.WxOauth2TokenService;
import com.imc.platform.base.wxOauth2Token.http.tuple.Oauth2TokenParms;
import com.imc.platform.base.wxOauth2Token.service.IOauthService;
import com.twp.common.component.process.exception.combo.IComboExecptionForTFunc;
import com.twp.common.tuple.ResultDTO;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/api/public/wx/index")
public class WxOauth2TokenController {

    @Autowired
    WxOauth2TokenService wxOauth2TokenService;
    @Autowired
    IOauthService oauthService;
    @Autowired
    MysqlUtil mysqlUtil;

    @Autowired
    UserRepository userRepository;

    @Autowired
    ISSOService ssoservice;

    @Autowired
    IComboExecptionForTFunc iComboExecptionForTFunc;

    @RequestMapping(value = "/getOpenIdByCode",method = RequestMethod.POST)
    @ResponseBody
    public ResultDTO getCode(@RequestBody Oauth2TokenParms params,HttpServletRequest request) {
        ResultDTO resultDTO = ResultDTO.builder().build();
        try {
            boolean check = (StringUtils.isEmpty(params.getJs_code()));
            if (check) {
                resultDTO.setIsSuccess(false);
                resultDTO.setMessage("CODE获取失败");
                return resultDTO;
            }
            String getOpenSesJson_ =wxOauth2TokenService.oauthLogin(
                    wxOauth2TokenService.beanToMap(
                            params
                    )
            );
            JSONObject getOpenSesJson = JSON.parseObject(getOpenSesJson_);
            if (!StringUtils.isEmpty(getOpenSesJson.getString("errcode"))) {
                resultDTO.setIsSuccess(false);
                resultDTO.setMessage("用户绑定失败");
                log.info("getOpenSesJson:"+JSON.toJSONString(getOpenSesJson));
                return resultDTO;
            }
            HttpSession session = request.getSession();
            log.info("wxData:"+getOpenSesJson_);
            session.setAttribute("wxData", getOpenSesJson);
            JSONObject retJsonObject=new JSONObject();
            retJsonObject.put("sessionId",session.getId());
            resultDTO.setData(retJsonObject);
            resultDTO.setIsSuccess(true);
            resultDTO.setMessage("查询成功");
        }catch(Exception e){
            e.printStackTrace();
            resultDTO.setIsSuccess(false);
            resultDTO.setMessage(e.getMessage());
        }
        return resultDTO;
    }

    /**
     *QY 2018/9/12 19:18
     *方法描述:解密用户信息
     **/
    @Logs
    @RequestMapping(value = "/wxBDUser",method = RequestMethod.POST)
    @ResponseBody
    public ResultDTO wxBDUser(@RequestBody Oauth2TokenParms parms, HttpServletRequest request){
        return iComboExecptionForTFunc.executeFlow(
                ResultDTO.builder().build(),
                (ResultDTO<Object> t) ->{
                    JSONObject getOpenSesJson = JSON.parseObject(wxOauth2TokenService.oauthLogin(
                            wxOauth2TokenService.beanToMap(
                                    parms
                            )
                    ));
                    log.info("wxDecrypt开始解码");
                    val ss = AESUtils.wxDecrypt(parms.getEncrypted(),getOpenSesJson.getString("session_key"),parms.getIv());
                    JSONObject getPhotoJson = JSONObject.parseObject(ss);
                    log.info("wxDecrypt解码完成");
                    String errcode = getPhotoJson.getString("errcode");
                    if(getPhotoJson==null || !StringUtils.isEmpty(errcode)){
                        t.setIsSuccess(false);
                        t.setMessage("注册失败");
                        return;
                    }
                    log.info("getPhotoJson:"+ss);
                    String phoneNumber = getPhotoJson.getString("phoneNumber");
                    String openid = getOpenSesJson.getString("openid");
                    String roleName = "";
                    User user = userRepository.findFirstByLoginName(phoneNumber);
                    if (user==null){
                        User dto = User
                                .builder()
                                .loginName(phoneNumber)
                                .tel(phoneNumber)
                                .openId(openid)
                                .createTime(DateUtils.getCurrentDate())
                                .build();
                        if (!StringUtils.isEmpty(parms.getChannel())){
                            dto.setChannel(parms.getChannel());
                        }
                        roleName = oauthService.addWXLogin(dto);
                    }else if (!user.getOpenId().equals(openid)){
                        user.setOpenId(openid);
                        userRepository.save(user);
                    }

                    if (StringUtils.isEmpty(roleName)){
                        roleName = user.getDuty();
                    }

                    Map<String,Object> map = new HashMap();

                    map.put("roleName",roleName);
                    map.put("openid",openid);
                    map.put("phoneNumber",phoneNumber);

                    HttpSession session = request.getSession();
                    map.put("sessionId",session.getId());
                    if (user==null){
                        user = userRepository.findFirstByLoginName(phoneNumber);
                    }
                    session.setAttribute("currentUser",user);

                    t.setMessage("用户注册成功");
                    t.setData(map);
                },
                (e,t)->{
                    t.setIsSuccess(false);
                    t.setMessage(e.getMessage());
                }
        );
    }

    @PostMapping("/keepLoginByPhoneNumber")
    @ResponseBody
    public ResultDTO SimpleLogin(HttpServletRequest request,@RequestBody Oauth2TokenParms params){
        return iComboExecptionForTFunc.executeFlow(
                ResultDTO.builder().build(),
                t->{
                    String phoneNumber = params.getPhoneNumber();
                    if (!StringUtils.isEmpty(phoneNumber)){
                        User user = userRepository.findFirstByLoginName(phoneNumber);
                        HttpSession session = request.getSession();
                        if (user!=null){
                            ssoservice.SSOLogin(user.getLoginName());
                            Map<String,Object> map = new HashMap<>();
                            map.put("sessionId",request.getSession().getId());
                            session.setAttribute("currentUser",user);
                            t.setData(map);
                        }
                    }
                },
                (e,t)->{
                    t.setIsSuccess(false);
                    t.setMessage("keepLogin失败");
                }
        );
    }

    @PostMapping("/keepLogin")
    @ResponseBody
    public ResultDTO SimpleLoginByOpenId(HttpServletRequest request,@RequestBody Oauth2TokenParms params){
        return iComboExecptionForTFunc.executeFlow(
                ResultDTO.builder().build(),
                t->{
                    String openid = params.getOpenid();
                    if (!StringUtils.isEmpty(openid)){
                        User user = userRepository.findAllByOpenId(openid);
                        HttpSession session = request.getSession();
                        if (user!=null){
                            ssoservice.SSOLogin(user.getLoginName());
                            Map<String,Object> map = new HashMap<>();
                            map.put("sessionId",request.getSession().getId());
                            session.setAttribute("currentUser",user);
                            t.setData(map);
                        }
                    }
                },
                (e,t)->{
                    t.setIsSuccess(false);
                    t.setMessage("keepLogin失败");
                }
        );
    }

}
